#include "imageviewer.h"
#include <QDebug>
#include <QFileDialog>
#include <QImage>
#include <QPainter>
#include <QMouseEvent>

ImageViewer::ImageViewer(QWidget *parent) : QWidget(parent)
{
    img = nullptr;
    pos = QPoint(0,0);
    index = 0;
    setFocus();
}

void ImageViewer::mouseDoubleClickEvent(QMouseEvent * event)
{
    //QString filename = QFileDialog::getOpenFileName(this);
    dirname = QFileDialog::getExistingDirectory();
    QDir dir(dirname);
    QStringList filter;
    filter << "*.png";
    filter << "*.jpg";
    filter << "*.gif";
    files = dir.entryList(filter);
    img = new QImage(dirname + "/" + files[index]);
    this->parentWidget()->resize(img->width(), img->height());//根据图像调整窗口大小
}

void ImageViewer::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Right)
    {
        if (index < files.size() - 1)
        {
            img = new QImage(dirname + "/" + files[++index]);
            this->parentWidget()->resize(img->width(), img->height());
            repaint();
        }
    }

    if (event->key() == Qt::Key_Left)
    {
        if (index > 0)
        {
            img = new QImage(dirname + "/" + files[--index]);
            this->parentWidget()->resize(img->width(), img->height());
            repaint();
        }
    }

    if (event->key() == Qt::Key_Escape)
    {
        this->parentWidget()->close();
    }
}

void ImageViewer::paintEvent(QPaintEvent *event)
{
    if (img)
    {
        QPainter painter(this);//在窗口上绘制图像
        painter.drawImage(0, 0, *img);
    }
}

void ImageViewer::mousePressEvent(QMouseEvent *event)
{
    pos = event->pos();//保存鼠标第一次按下的位置
}

void ImageViewer::mouseMoveEvent(QMouseEvent *event)
{

    if (img)
    {
        QPainter painter(img);//在图像上绘制线段
        QPen pen;
        pen.setColor(QColor(0, 0, 255));
        pen.setWidth(10);
        painter.setPen(pen);
        painter.drawLine(pos, event->pos());//连接两个点
        pos = event->pos();
        repaint();  //触发paint事件，重新在窗口上绘制图像
    }
}
